from flask import Blueprint, request, jsonify
from app.utils.file_processor import process_uploaded_file
from app.utils.ollama_client import generate_response

bp = Blueprint('api', __name__, url_prefix='/api/v1')


@bp.route('/process', methods=['POST'])
def process():
    try:
        text_input = request.form.get('text', '')
        file = request.files.get('file')

        file_content = process_uploaded_file(file) if file else ''
        combined_input = f"{text_input}\n{file_content}".strip()

        if not combined_input:
            return jsonify({
                "error": "至少需要提供文本输入或有效文件",
                "code": "INVALID_INPUT"
            }), 400

        response = generate_response(combined_input)
        return jsonify({
            "data": {
                "response": response,
                "tokens_used": len(response.split())
            }
        })

    except Exception as e:
        return jsonify({
            "error": str(e),
            "code": "SERVER_ERROR"
        }), 500